package com.netty4.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;

import java.net.InetSocketAddress;

public class NettyClient {
    private static Bootstrap bootstrap;

    public static void main(String[] args) {
        for (int i = 0; i <3 ; i++) {
            new Thread(new MyThread()).start();
        }
    }

    static class MyThread implements  Runnable{

        public void run() {
            connect("10.130.13.57",8080);
        }
        public void connect(String host,int port){
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
                bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel){
                        socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(31)).addLast(new FirstClientHandler());
                    }
                });
                ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)).sync();
                System.out.println(Thread.currentThread().getName() + ",客户端发起异步连接..........");
                /**等待客户端链路关闭*/
                future.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                /**优雅退出，释放NIO线程组*/
                group.shutdownGracefully();
            }
        }
    }
}
